﻿
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using FastDFS.Client;
using Microsoft.Extensions.Options;

namespace CK.Sprite.FileStorage
{
    public class FastDfsStorageProvider : StorageProvider
    {
        private TrackerServer _trackerServer;
        private readonly TrackerGroup _trackerGroup;
        public FastDfsStorageProvider(FastDfsOptions options) : base(options)
        {
            _trackerGroup = new TrackerGroup(options.Trackers.Select(ipAndPort =>
            {
                var ipAndPortArray = ipAndPort.Split(':');
                return new IPEndPoint(IPAddress.Parse(ipAndPortArray[0]), int.Parse(ipAndPortArray[1]));
            }).ToArray());
        }

        private async Task<TrackerServer> GetTrackerServerAsync()
        {
            if (_trackerServer == null)
            {
                // 暂时没有添加心跳
                var tracker = new TrackerClient(_trackerGroup);
                _trackerServer = await tracker.GetConnectionAsync();
            }
            return _trackerServer;
        }

        private async Task<StorageClientEx> GetClient()
        {
            return new StorageClientEx(await GetTrackerServerAsync(), null);
        }

        public override async Task<string[]> StoreAsync(string fileName, string ext, string groupName = null)
        {
            var client = await GetClient();
            if (string.IsNullOrEmpty(ext)) ext = Alphaleonis.Win32.Filesystem.Path.GetExtension(fileName).Trim('.');
            var result = await client.UploadFileAsync(fileName, ext, null);
            return CreateResult(result);
        }

        public override async Task<string[]> StoreAsync(Stream fileStream, string ext, string groupName = null)
        {
            var client = await GetClient();
            var result = await client.UploadFileAsync(fileStream, ext, null);
            return CreateResult(result);
        }

        //public override async Task<object> StatisticAsync()
        //{
        //    var trackerClient = new TrackerClient(this._trackerGroup);
        //    TrackerServer server = await GetTrackerServerAsync();
        //    var groups = await trackerClient.ListGroupsAsync(server);
        //    return new
        //    {
        //        Provider = "FastDFS",
        //        Groups = groups
        //    };
        //}

        private string[] CreateResult(string[] result)
        {
            var url = string.Join(UrlSeparator, Options.HttpDomain, result[0], result[1]);
            return new[] { url, string.Join(UrlSeparator, result[0], result[1]) };
        }

        public override async Task<int> DownloadFileAsync(string remoteFilename, string localFilename, string groupName = null)
        {
            var client = await GetClient();
            var result = await client.DownloadFileAsync(groupName, remoteFilename, localFilename);
            return result;
        }

        public override async Task<int> DeleteFileAsync(string remoteFilename, string groupName = null)
        {
            var client = await GetClient();
            var result = await client.DeleteFileAsync(groupName, remoteFilename);
            return result;
        }

        public override string CalculateDownServerPath(string serverPath, string fileName)
        {
            if(string.IsNullOrEmpty(serverPath))
            {
                return "";
            }
            if(serverPath.StartsWith("http"))
            {
                return serverPath;
            }
            return Options.HttpDomain + serverPath + "?attname=" + fileName;
        }
    }
}